import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * JDBC 编程 和数据库建立链接 关闭资源
 */

/**
 * 使用 JDBC 基本流程
 * 1.创建数据源
 * 2.和数据库建立链接
 * 3.构造 sql 语句
 * 4.执行 sql 语句
 * 5.如果是查询语句，需要遍历结果集，如果是插入/删除/修改，则不需要
 * 6.关闭连接，释放资源
 */

public class DBUtil {
    private static final String URL = ("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
    private static final String USERNAME = "root";
    private static final String PASSWORD = "707703";


    private volatile static DataSource dataSource = null;

    private static DataSource getDataSource() {
        if(dataSource == null) {
            synchronized (DBUtil.class) {
                if(dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setUrl(URL);
                    ((MysqlDataSource)dataSource).setUser(USERNAME);
                    ((MysqlDataSource)dataSource).setPassword(PASSWORD);
                }
            }
        }
        return dataSource;
    }


    //建立链接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }


    //关闭连接
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet)  {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}
